package com.fable.web.common.admin;

import com.fable.common.constant.FableConstant;
import com.fable.dal.dto.AdminUserDTO;
import com.fable.dal.model.AdminDO;
import com.fable.dal.model.AdminUserDO;

import javax.servlet.http.HttpSession;

/**
 * Created by weishuai on 15/12/25.
 */
public class UserTools {

    private static final ThreadLocal<AdminUserDTO> admin = new ThreadLocal<AdminUserDTO>();

    private String loginName;
    private Long loginId;

    private String role;

    public static AdminUserDTO getAdmin() {
        return admin.get();
    }

    public static final void setAdmin(AdminUserDTO adminDO){
        admin.set(adminDO);
    }
    public static final void removeAdmin(){
        admin.remove();
    }

    public static void setCurrentUser(HttpSession session,AdminUserDTO adminUserDTO){
        session.setAttribute(FableConstant.USER_SESSION_KEY, adminUserDTO);
        UserTools.setAdmin(adminUserDTO);
    }
    public static void removeCurrentUser(HttpSession session){
        session.removeAttribute(FableConstant.USER_SESSION_KEY);
        UserTools.removeAdmin();
    }

    public static Long getLoginId(HttpSession session){
        AdminUserDTO adminUserDTO =(AdminUserDTO)session.getAttribute(FableConstant.USER_SESSION_KEY);
        if(adminUserDTO!=null){
            return Long.parseLong(adminUserDTO.getId()+"");
        }
        return 0L;
    }


    public static AdminUserDTO getAdminUser(HttpSession session){
        AdminUserDTO adminUserDTO =(AdminUserDTO)session.getAttribute(FableConstant.USER_SESSION_KEY);
        if(adminUserDTO!=null){
            return adminUserDTO;
        }
        return null;
    }

    @Deprecated
    public static String getLoginName() {
        try {
            return admin.get().getLogin();
        } catch (Exception e) {
            return "";
        }
    }

    @Deprecated
    public static Integer getLoginId() {
        try {
            return admin.get().getId();
        } catch (Exception e) {
            return 0;
        }
    }

    @Deprecated
    public static String getRole() {
        try {
            return admin.get().getRoleName();
        } catch (Exception e) {
            return "";
        }
    }

    public void setLoginName(String loginName) {
        this.loginName = loginName;
    }
}
